/**
 * weapp-js v1.7.1(2021-4-16)
 * https://codeup.aliyun.com/motigo/motigo/weapp_base
 * Copyright@ 2021 Motigo, Inc.
 * 
 */
import base_request from './base_request.js';
export default {
    ERR_CANCEL: -100,
    ERR_UNKNOWN: -101,

    createOrder(opts) {
        return this._create_order(
            base_request.appid,
            base_request.openid,
            opts.title,
            opts.price,
            opts.detail);
    },

    submitPayment(order_info) {
        return new Promise((resolve, reject) => {
            wx.requestPayment({
                timeStamp: order_info.pay_args.timestamp + '',
                nonceStr: order_info.pay_args.noncestr,
                package: order_info.pay_args.package,
                signType: 'MD5',
                paySign: order_info.pay_args.pay_sign,
                success() {
                    resolve({
                        order_id: order_info.order_id
                    });
                },
                fail: res => {
                    let ret = -1;
                    let msg = '';
                    if (res.errMsg.indexOf('cancel') > -1) {
                        ret = this.ERR_CANCEL;
                        msg = 'canceled'
                    }

                    reject({
                        ret: ret,
                        msg: msg
                    });
                }
            });
        });
    },
    createAndSubmit(opts) {
        return this.createOrder(opts).then(this.submitPayment.bind(this));
    },
    _create_order(appid, openid, title, price, detail) {
        return new Promise((resolve, reject)=>{
            base_request.post('/payment/order/' + appid, {
                openid: openid,
                title: title,
                price: price,
                detail: detail
            }).then(data=>{
                if(data && data.pay_args) {
                    resolve(data);
                } else {
                    reject({
                        msg: '创建微信支付订单失败!'
                    })
                }
            }, reject);
        });
    },
    pay(appid, openid, title, price, detail) {
        return new Promise((resolve, reject) => {
            this._create_order(appid, openid, title, price, detail).then(res => {
                if(res && res.pay_args) {
                    this.submitPayment(res).then(resolve, reject);
                } else {
                    reject({
                        ret: this.ERR_UNKNOWN,
                        msg: '获取支付参数失败!'
                    });
                }
            }, err => {
                reject(err);
            })
        })
    }
}
